#!/bin/bash
#yum-cron的监控脚本
OK=0
WARN=1
CRITICAL=2
UNKNOWN=3
PATH="/bin:/sbin:/usr/bin:/usr/sbin"
HName=`/bin/hostname -s`
Ok_name=''
Fail_name=''
Judge=0
TTimeout=2

#######add by zhengw #######
os_version=$(cat /etc/redhat-release)

if [[ "$os_version" == "AlmaLinux release 9.4 (Seafoam Ocelot)" ]]; then
    os_status="$os_version that is OK"
else
    echo "/etc/redhat-release is $os_version that is wrong"
    exit 2
fi


TT=`uname -r`

if [ "$TT" == "5.14.0-427.26.1.el9_4.x86_64" ]
#if [ "$TT" = "3.10.0-1160.105.1.el7.x86_64" -o "$TT" = "5.14.0-362.13.1.el9_3.x86_64" ]   #5.14.0-362.13.1.el9_3.x86_64
then
        echo "$os_status,  Kernal name is:$TT"
        exit 0
else
        echo "Kernal name is:$TT, the right Kernal name is: 5.14.0-427.26.1.el9_4.x86_64"
        exit 2
fi
#############################



start_checktime=`date '+%s'`
check_name="check_yum-cron"

check_os=$(grep "Scientific Linux" /etc/issue | wc -l)
#check_os=$(head -n 1 /etc/issue | awk -F " "'{print $1}')
if [ $check_os -gt 0 ]
then
    OK_name="Scientific Linux release 6.9 does not need to monitor yum-cron"
    echo "{\"$HName\":$OK_name}"
    exit $OK
fi

if [ ! -e "/var/log/yum-cron.log" ]
then
    Unkown_name="/var/log/yum-cron.log was not found!"
    echo "{\"$HName\":$Unkown_name}"
    exit $UNKNOWN
fi
#执行yum-cron时，如果没有更新，则没有任何输出,但是log里面会增加一条日期和hostname
check_update=$(tail -n 1 /var/log/yum-cron.log)
if [ "$check_update"x = "$HName"x ]
then
    Ok_name="yum-cron does not have any updates!"
    echo "{\"$HName\":$Ok_name}"
    exit $OK
fi

check_result=$(grep -E 'error|successfully' /var/log/yum-cron.log| tail -n 1)
#check_result=$(grep -E 'error|successfully' /root/yum-cron.log| tail -n 1)
#fail字符串最后有一个空格
fail="Failed to check for updates with the following error message: "
success_download="Updates downloaded successfully."
success_apply="The updates were successfully applied"
# "$check_result"两边加"",否则报错
# "$check_result"x最后的x，这是特意安排的，因为当$check_result为空的时候，上面的表达式就变成了x = "$fail"x，显然是不相等的。而如果没有这个x，表达式就会报错：[: =: unary operator expected
if [ "$check_result"x == "$fail"x ]
then
    Fail_name="Failed to check for updates!"
    echo "{\"$HName\":$Fail_name}"
    exit $CRITICAL
elif [ "$check_result"x = "$success_apply"x ]
then
    Ok_name="yum-cron updates were successfull applied!"
    echo "{\"$HName\":$Ok_name}"
    exit $OK
elif [ "$check_result"x = "$success_download"x ]
then
    Ok_name="yum-cron updates were successfull downloaded but not applied!"
    echo "{\"$HName\":$Ok_name}"
    exit $OK
else
    Unkown_name="Failed to query the yum-cron execution result!"
    echo "{\"$HName\":$Unkown_name}"
    exit $UNKNOWN
fi
